/*GLOBAL VARIABLES*/
var blankString = /^\s*$/;

/* ENUMs */
var resultForm = "RESULT_FORM";
var userForm = "USER_FORM";

function getAllElementChilds(elementId, tagName) {
	var forms = document.getElementById(elementId);
	return forms.getElementsByTagName(tagName);
}

function addNewDivUSER() {
	var i = getAllElementChilds("formsList", "li").length;
	var list = document.getElementById("formsList");
	var newRow = document.createElement("li");

	var newCourseInput = document.createElement("input");
	newCourseInput.type = "text";
	newCourseInput.id = "courseInput_" + i;
	newRow.appendChild(newCourseInput);
	list.appendChild(newRow);

	var codeinputId = "codeInput_" + i;
	var spanText = "<span><input type='text' id='" + codeinputId + "' /></span>";
	$("ul").find("li:eq(" + i + ")").prepend(spanText);

}

function addNewDivFORM() {
	var i = getAllElementChilds("formsList", "li").length;
	var list = document.getElementById("formsList");
	var newRow = document.createElement("li");

	var newDatepicker = document.createElement("input");
	newDatepicker.className = "inputText";
	newDatepicker.id = "datepicker_" + i;
	newRow.appendChild(newDatepicker);

	var newCourseSelect = document.createElement("select");
	newCourseSelect.id = "courseSelect_" + i;
	addOptionsToSelect(newCourseSelect, coursesForSelect, true);
	newRow.appendChild(newCourseSelect);

	var newMethodSelect = document.createElement("select");
	newMethodSelect.id = "methodSelect_" + i;
	addOptionsToSelect(newMethodSelect, methodsForSelect, true);
	newRow.appendChild(newMethodSelect);

	var newHour = document.createElement("input");
	newHour.type = "text";
	newHour.id = "hour_" + i;
	newRow.appendChild(newHour);

	list.appendChild(newRow);
	$("#datepicker_" + i).datepicker();
	$("#datepicker_" + i).datepicker("option", "dateFormat", "dd.mm.yy");
}

function getElementsByTagNames(list, obj) {
	var result = [], elms;
	obj = obj || document;
	var tags = {};
	for ( var i = 0; i < list.length; i++)
		tags[list[i].toUpperCase()] = true;
	elms = obj.getElementsByTagName('*');
	for (i = 0; i < elms.length; i++)
		if (elms[i].tagName in tags)
			result.push(elms[i]);
	return result;
}

// Collects all inputs by row - result:
// { [row1_value, row1_value, row1_value], [row2_value, row2_value, row2_value], [... }
function getByRow() {
	var inputsByRow = [];
	var childs = getAllElementChilds("formsList", "li");
	for ( var i = 0; i < childs.length; i++) {
		var inputs = getElementsByTagNames([ 'input', 'select' ], childs[i]);
		var args = [];
		for ( var j = 0; j < inputs.length; j++) {
			args.push(inputs[j].value);
		}
		inputsByRow.push(args);
	}
	return inputsByRow;
}

function save(formToValidate) {
	var results = [];
	var allValid = true;
	var inputsByRow = getByRow();
	for ( var i = 0; i < inputsByRow.length; i++) {
		var args = inputsByRow[i];
		// Before saving control, if all inputs exist in all rows; also
		// control, if they are in appropriate type (i.e. double)
		if (!allDataExist(args) || !validForm(args, formToValidate)) {
			if (isEmptyRow(args)) {
				setIsValidRow(formToValidate, i);
			} else {
				allValid = false;
				setNotValidRow(formToValidate, i);
			}
		} else {
			setIsValidRow(formToValidate, i);
			results.push(args);
		}
	}

	// If not rows contain all data (empty rows not in count)
	if (!allValid) {
		return;
	}

	if (results.length == 0) {
		alert("No results are added");
		return;
	}

	if (formToValidate === userForm) {
		var semesterId = document.getElementById("semesterSelect").value;
		saveCourses(semesterId, results);
	} else if (formToValidate === resultForm) {
		alert('saving ' + JSON.stringify(results));
		saveResults(results);
	}
}

// Function that marks input or select to red
function setNotValidRow(formToValidate, idx) {
	if (formToValidate === userForm) {
		document.getElementById("courseInput_" + idx).className = "notValid";
		document.getElementById("codeInput_" + idx).className = "notValid";
	} else if (formToValidate === resultForm) {
		document.getElementById("datepicker_" + idx).className = "datePickerNotValid";
		document.getElementById("courseSelect_" + idx).className = "notValid";
		document.getElementById("methodSelect_" + idx).className = "notValid";
		document.getElementById("hour_" + idx).className = "notValid";
	}
}

// Function that marks input or select from red to normal state
function setIsValidRow(formToValidate, idx) {
	if (formToValidate === userForm) {
		document.getElementById("courseInput_" + idx).className = "valid";
		document.getElementById("codeInput_" + idx).className = "valid";
	} else if (formToValidate === resultForm) {
		document.getElementById("datepicker_" + idx).className = "inputText";
		document.getElementById("courseSelect_" + idx).className = "valid";
		document.getElementById("methodSelect_" + idx).className = "valid";
		document.getElementById("hour_" + idx).className = "valid";
	}
}

/* FUNCTIONS FOR SAVING USER COURSES AND RESULTS */
function saveCourses(semesterId, courses) {
	$.ajax({
		type : "POST",
		data : {
			"action" : "save",
			"semesterId" : semesterId,
			"courses" : JSON.stringify(courses)
		},
		dataType : "json",
		url : "CourseData"
	}).success(function(response) {
		self.location = "form.jsp";
	});
}

function saveResults(results) {
	$.ajax({
		type : "POST",
		data : {
			"action" : "save",
			"results" : JSON.stringify(results)
		},
		dataType : "json",
		url : "ResultData"
	}).success(function(response) {
		alert("success");
		// self.location = "form.jsp";
	});
}

// FUNCTIONS FOR VALIDATING THE FORM
// Function for controlling if all data exists in input; no null's
function allDataExist(arr) {
	for ( var i in arr) {
		if (arr[i].match(blankString) !== null) {
			return false;
		}
	}
	return true;
}

// Function which controls, if row is fully empty; all inputs are empty
function isEmptyRow(arr) {
	var emptyInputs = 0;
	for ( var i in arr) {
		if (arr[i].match(blankString) !== null) {
			emptyInputs++;
		}
	}
	if (emptyInputs == arr.length) {
		return true;
	}
	return false;
}

// Function which controls, if date and integer inputs are in appropriate type
function validForm(arr, formToValidate) {
	// TODO validate date
	// ...
	if (formToValidate === resultForm) {
		// TODO implement - if separator is comma?
		// Control if hour inputs are type of double (separator must be '.' not ',')
		var hour = arr[3];
		if (!isDouble(hour)) {
			return false;
		}
	}
	return true;
}

function isDouble(input) {
	return input.match(/^\d+\.?\d*$/) !== null;
}

/* ADDITIONAL FUNCTIONS */

function divideHours() {
	var inputsByRow = getByRow();
	var insertedRowIndexes = [];
	for ( var i = 0; i < inputsByRow.length; i++) {
		var args = inputsByRow[i];
		if (isEmptyRow(args)) {
			continue;
		}
		insertedRowIndexes.push(i);
	}
	var rowCount = insertedRowIndexes.length;
	var hourValue = getDividedHourValue(rowCount);
	if (hourValue === null) {
		return;
	}
	for ( var j = 0; j < rowCount; j++) {
		document.getElementById("hour_" + insertedRowIndexes[j]).value = hourValue.toFixed(2);
	}
}

function getDividedHourValue(rowCount) {
	var fullHoursElement = document.getElementById("hoursDivisionInput");
	var fullHours = fullHoursElement.value;
	if (isDouble(fullHours)) {
		fullHoursElement.style.marginTop = "5px";
		fullHoursElement.style.borderStyle = "none";
		return fullHours / rowCount;
	} else {
		fullHoursElement.style.marginTop = "4px";
		fullHoursElement.style.border = "1px solid red";
	}
	return null;
}
